//
//  SAPrintSettingsVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/5/11.
//

#import "SAPrintSettingsVC.h"
#import "SAGlobalSettingsSectionHeader.h"
#import "SAGlobalSettingsTitleSectionHeader.h"
#import "SAGlobalSettingsSectionFooterView.h"
#import "SAGlobalSettingsCell.h"
#import "SAGlobalSettingsLabelCell.h"
#import "SASystemSettingsListAPI.h"
#import "SASystemSettingsCheckAPI.h"
#import "BluetoothDisplayView.h"
#import "SACloudPrintHeartbeatAPI.h"
#import "ConnecterManager.h"
#import "SAPrinterSetting.h"
#import "SALabelSettingModel.h"

@interface SAPrintSettingsVC ()<UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate,CAAnimationDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataArr;
@property (nonatomic, strong) NSMutableArray<SALabelSettingModel *> *labelMarr;
@property (nonatomic,   copy) NSString *printerName;
@property (nonatomic, strong) NSString *printerStatus;
@property (nonatomic, assign) NSInteger printerNum;

@property (nonatomic, strong) SASystemSettingsListAPI *systemSettingsListAPI;
@property (nonatomic, strong) SASystemSettingsCheckAPI *systemSettingsCheckAPI;
@property (nonatomic,   weak) BluetoothDisplayView *bluetoothDisplayView;
@property (nonatomic, strong) SACloudPrintHeartbeatAPI *cloudPrintHeartbeatAPI;

@property (nonatomic, strong) SAOverallSetting *overallSetting;
@property (nonatomic, strong) CBPeripheral *peripheral;
@property (nonatomic, strong) NSString *printName;
@property (nonatomic, assign) NSInteger signal;
@property (nonatomic, assign) NSInteger signal2;
@property (nonatomic, assign) NSInteger signal3;

@property (nonatomic, assign) BOOL isConnection;

@property (nonatomic, assign) BOOL isTip;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) int count;

@end

@implementation SAPrintSettingsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.overallSetting = [SAOverallSetting shareInstance];
    self.peripheral = nil;
    [self setBgImage:nil];
    //无需释放，因为vc不可能被释放
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(againConnection) name:@"IntoTheFrontDesk" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(overallSettingDidChanged) name:@"kOverallSettingDidChanged" object:nil];
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.systemSettingsListAPI == api) {
        NSDictionary *dataDic = data[@"data"];
        // 打印机设置
        NSDictionary *printerSettingDic = dataDic[@"printer_setting"];
        self.printerNum = [printerSettingDic[@"sales_print_copies"][@"value"] integerValue];//  打印份数：0-不打印 1-打印1份 2-打印2份
        self.overallSetting.printerSetting.printCopies = self.printerNum;
        self.systemSettingsCheckAPI.settingsId = printerSettingDic[@"sales_print_copies"][@"settingsId"];
        self.systemSettingsCheckAPI.parentId = printerSettingDic[@"sales_print_copies"][@"parentId"];
        [self.tableView reloadData];
    }else if (self.systemSettingsCheckAPI == api) {
        self.printerNum = [self.systemSettingsCheckAPI.value integerValue];
        self.overallSetting.printerSetting.printCopies = self.printerNum;
        [self.tableView reloadData];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    
}

- (void)initData {
    self.printerName = @"Printer";
    self.printerStatus = @"打印机未连接";
    if ([SAOverallSetting shareInstance].printerSetting.printerStatus == 2) {
        self.printerName = [SAOverallSetting shareInstance].printerSetting.printerBleName;
        self.printerStatus = @"打印机已连接";
    }
}

#pragma mark - event

- (void)scrollToTopAction {
    //    [self.tableView scrollToTop];
}


-(void)backToLastVC {
    CATransition *transition =[ CATransition animation];
    transition.duration = 0.3f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionPush;
    transition.subtype = kCATransitionFromLeft;
    transition.delegate = self;
    [self.view.superview.layer addAnimation:transition forKey:nil];
    [self.view removeFromSuperview];
}

-(void)canclePrint {
    self.isTip = NO;
    [self startTime];
    
    self.isConnection = NO;
    self.signal = 0;
    self.signal2 = 0;
    self.signal3 = 0;
    self.overallSetting.printerSetting.printerStatus = 0;
    [[BluetoothManager sharedInstance] cancelConnect];
    Manager.bleConnecter = nil;
    [Manager close];
    self.printerName = @"Printer";
    self.printerStatus = @"打印机未连接";
    [self.tableView reloadData];
}

- (void)Printer {
    /* 扫描 */
    WeakSelf
    self.signal = 0;
    __block int printNum = 0;
    NSMutableArray *peripheralArray = [NSMutableArray array];
    [Manager scanForPeripheralsWithServices:nil options:nil discover:^(CBPeripheral * _Nullable peripheral, NSDictionary<NSString *,id> * _Nullable advertisementData, NSNumber * _Nullable RSSI) {
        if (!self.bluetoothDisplayView) {
            self.bluetoothDisplayView = [BluetoothDisplayView show:self.view];
        }
        if (peripheral.name.length > 0) {
            if ([peripheralArray containsObject:peripheral] != YES) {
                [peripheralArray addObject:peripheral];
            }
        }
        [self.bluetoothDisplayView update:peripheralArray];
        
        self.bluetoothDisplayView.connectPeripheralBlock = ^(CBPeripheral * _Nonnull peripheral) {
            
            // 打印机正在连接中
            self.printerStatus = @"打印机正在连接";
            [self.tableView reloadData];
            weakSelf.isConnection = YES;
            weakSelf.isTip = NO;
            [weakSelf startTime];
            
            NSString *printOpen = kPrintOpen;
            NSString *printType = kPrintType;
            
            if ([peripheral.name isEqualToString:@"MHT-P58D"] || [peripheral.name isEqualToString:@"YDT-XP"] || ([printOpen integerValue] == 1 && [peripheral.name isEqualToString:@"MHT-P18L"] && [printType integerValue] == 1)) {
                [Manager stopScan];
                self.overallSetting.printerSetting.printerBleName = peripheral.name;
                [kUserDefault setObject:peripheral.name forKey:kPrintKey];
                [weakSelf ecsAndTsp];
                return;
            }
            
            [Manager connectPeripheral:peripheral options:nil timeout:2 connectBlack:^(ConnectState state) {
                if (state == CONNECT_STATE_CONNECTED) {
                    weakSelf.overallSetting.printerSetting.printType = 2;
                    weakSelf.overallSetting.printerSetting.printerStatus = 2;
                    weakSelf.overallSetting.printerSetting.printerBleName = peripheral.name;
                    [kUserDefault setObject:peripheral.name forKey:kPrintKey];
                    if (printNum == 0) {
                        printNum ++;
                        [weakSelf ecsAndTsp];
                    }
                    BLEConnecter *bleConnecter = Manager.bleConnecter;
                    [Manager stopScan];
                    self.signal = 1;
                }else {
                    if (self.signal == 0) {
                        self.printerStatus = @"打印机未连接";
                        self.printerName = @"Printer";
                        self.overallSetting.printerSetting.printerStatus = 0;
                        [self.tableView reloadData];
                    }
                    [Manager stopScan];
                }
            }];
        };
        
        self.bluetoothDisplayView.hideBlock = ^{
            [Manager stopScan];
        };
        self.bluetoothDisplayView.hideBlock = ^{
            [Manager stopScan];
        };
    }];
}

-(void)overallSettingDidChanged {
    self.printerStatus = @"打印机未连接";
    if ([SAOverallSetting shareInstance].printerSetting.printerStatus == 2) {
        self.printerStatus = @"打印机已连接";
    }
    [self.tableView reloadData];
}

//从后台进入前台进行重新连接
-(void)againConnection {
    if (self.overallSetting.printerSetting.printerBleName.length == 0) return;
    if (self.isConnection == NO) return;
    if ([SAValueManger shareInStance].printType == 1) {
        [self connectionBluetooth];
    }else if ([SAValueManger shareInStance].printType == 2) {
        [self startScane];
    }
}

#pragma mark - UITableView Delegate & DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.labelMarr.count;
    }
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        SAGlobalSettingsLabelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAGlobalSettingsLabelCell"];
        SALabelSettingModel *model = self.labelMarr[indexPath.row];
        cell.model = model;
        cell.textBlock = ^(NSString * str) {
            model.content = str;
            if ([model.titleStr isEqualToString:@"标签左偏移值"]) {
                [kUserDefault setObject:str forKey:kPrintLeftKey];
            } else if ([model.titleStr isEqualToString:@"标签顶部偏移值"]) {
                [kUserDefault setObject:str forKey:kPrintTopKey];
            } else if ([model.titleStr isEqualToString:@"切换打印方向"]) {
                [kUserDefault setObject:str forKey:kPrintDirectionKey];
            }
        };
        return cell;
    }
    SAGlobalSettingsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAGlobalSettingsCell"];
    UIColor *colour = kBlackColor;
    if (self.printerNum == indexPath.row) {
        colour = kBuleColor;
    }
    [cell refreshCellWithTitle:self.dataArr[indexPath.row] AndColour:colour];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        SAGlobalSettingsTitleSectionHeader *titleHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SAGlobalSettingsTitleSectionHeader"];
        return titleHeader;
    }
    SAGlobalSettingsSectionHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SAGlobalSettingsSectionHeader"];
    WeakSelf
    header.printerStatusBlock = ^{
        if (weakSelf.isTip == NO) {//打印机 频繁连接或断开 会闪退
            [Prompt popPromptViewWithMsg:@"不要频繁连接或断开打印机" duration:3];
        }else {
            if ([weakSelf.printerStatus isEqualToString:@"打印机已连接"]){
                [weakSelf canclePrint];
            }else {
                [weakSelf bleConnecter];
            }
        }
    };
    [header refreshHeaderWithPrinterName:self.printerName printerStatus:self.printerStatus];
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 40;
    }
    return 114;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    SAGlobalSettingsSectionFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SAGlobalSettingsSectionFooterView"];
    return footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }
    return 150;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        self.systemSettingsCheckAPI.value = [NSString stringWithFormat:@"%zd", indexPath.row];
        [self.systemSettingsCheckAPI sendRequestToServerWithActivityViewAndMask:POST];
    }
}

#pragma mark - initUI

- (void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"打印机连接"];
    self.printerNum = 0;
    self.isConnection = NO;
    self.isTip = YES;
    
    NSString *printLeft = kPrintLeft;
    NSString *printTop = kPrintTop;
    NSString *printDirection = kPrintDirection;
    if (printLeft == nil || printLeft.length == 0) {
        printLeft = @"0";
    }
    
    if (printTop == nil || printTop.length == 0) {
        printTop = @"0";
    }
    
    if (printDirection == nil || printDirection.length == 0) {
        printDirection = @"0";
    }
    
    self.labelMarr = [NSMutableArray array];
    SALabelSettingModel *model1 = [SALabelSettingModel new];
    model1.titleStr = @"标签左偏移值";
    model1.content = printLeft;
    model1.type = @"0";
    [self.labelMarr addObject:model1];
    
    SALabelSettingModel *model2 = [SALabelSettingModel new];
    model2.titleStr = @"标签顶部偏移值";
    model2.content = printTop;
    model2.type = @"0";
    [self.labelMarr addObject:model2];
    
    SALabelSettingModel *model3 = [SALabelSettingModel new];
    model3.titleStr = @"切换打印方向";
    model3.content = printDirection;
    model3.type = @"1";
    [self.labelMarr addObject:model3];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(kScaleNum(StatusHeight), 0, 0, 0));
    }];
    
    [self.systemSettingsListAPI sendRequestToServerWithActivityViewAndMask:GET];
}

#pragma mark - lazy init

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.backgroundColor = kLineColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.bounces = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[SAGlobalSettingsCell class] forCellReuseIdentifier:@"SAGlobalSettingsCell"];
        [_tableView registerClass:[SAGlobalSettingsLabelCell class] forCellReuseIdentifier:@"SAGlobalSettingsLabelCell"];
        [_tableView registerClass:[SAGlobalSettingsSectionHeader class] forHeaderFooterViewReuseIdentifier:@"SAGlobalSettingsSectionHeader"];
        [_tableView registerClass:[SAGlobalSettingsTitleSectionHeader class] forHeaderFooterViewReuseIdentifier:@"SAGlobalSettingsTitleSectionHeader"];
        [_tableView registerClass:[SAGlobalSettingsSectionFooterView class] forHeaderFooterViewReuseIdentifier:@"SAGlobalSettingsSectionFooterView"];
    }
    return _tableView;
}

- (NSArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSArray arrayWithObjects:@"不打印", @"打印1份", @"打印2份", @"打印3份", @"打印4份", nil];
    }
    return _dataArr;
}

-(SASystemSettingsListAPI *)systemSettingsListAPI {
    if (!_systemSettingsListAPI) {
        _systemSettingsListAPI = [SASystemSettingsListAPI apiWithDelegate:self];
    }
    return _systemSettingsListAPI;
}

-(SASystemSettingsCheckAPI *)systemSettingsCheckAPI {
    if (!_systemSettingsCheckAPI) {
        _systemSettingsCheckAPI = [SASystemSettingsCheckAPI apiWithDelegate:self];
    }
    return _systemSettingsCheckAPI;
}

-(SACloudPrintHeartbeatAPI *)cloudPrintHeartbeatAPI {
    if (!_cloudPrintHeartbeatAPI) {
        _cloudPrintHeartbeatAPI = [SACloudPrintHeartbeatAPI apiWithDelegate:self];
    }
    return _cloudPrintHeartbeatAPI;
}

-(void)bleConnecter {
    if (Manager.bleConnecter == nil) {
        [Manager didUpdateState:^(NSInteger state) {
            switch (state) {
                case CBCentralManagerStateUnsupported:
                    NSLog(@"The platform/hardware doesn't support Bluetooth Low Energy.");
                    break;
                case CBCentralManagerStateUnauthorized:
                    NSLog(@"The app is not authorized to use Bluetooth Low Energy.");
                    break;
                case CBCentralManagerStatePoweredOff:
                    NSLog(@"Bluetooth is currently powered off.");
                    break;
                case CBCentralManagerStatePoweredOn:
                    [self Printer];
                    NSLog(@"Bluetooth power on");
                    break;
                case CBCentralManagerStateUnknown:
                default:
                    break;
            }
        }];
    } else {
        [self Printer];
    }
}

-(void)startScane {
    if (self.isConnection == NO) {
        return;
    }
    __block int i = 0;
    __weak typeof(self) weakSelf = self;
    NSString *printName = [NSString stringWithFormat:@"%@",self.overallSetting.printerSetting.printerBleName];
    self.printName = printName;
    [[BluetoothManager sharedInstance] cancelConnect];
    self.overallSetting.printerSetting.printType = 0;
    __block int printNum = 0;
    self.signal = 0;
    NSString *printOpen = kPrintOpen;
    NSString *printType = kPrintType;
    if ([printName isEqualToString:@"MHT-P58D"] || [printName isEqualToString:@"YDT-XP"] || ([printOpen integerValue] == 1 && [printName isEqualToString:@"MHT-P18L"] && [printType integerValue] == 1)) {
        [kUserDefault setObject:printName forKey:kPrintKey];
        [weakSelf ecsAndTsp];
        return;
    }
    [Manager scanForPeripheralsWithServices:nil options:nil discover:^(CBPeripheral * _Nullable peripheral, NSDictionary<NSString *,id> * _Nullable advertisementData, NSNumber * _Nullable RSSI) {
        i++;
        if (peripheral.name != nil) {
            if ([peripheral.name isEqualToString:printName]) {
                [Manager connectPeripheral:peripheral options:nil timeout:2 connectBlack:^(ConnectState state) {
                    if (state == CONNECT_STATE_CONNECTED) {
                        if (printNum == 0) {
                            printNum ++;
                            [weakSelf ecsAndTsp];
                        }
                        BLEConnecter *bleConnecter = Manager.bleConnecter;
                        weakSelf.overallSetting.printerSetting.printType = 2;
                        weakSelf.overallSetting.printerSetting.printerStatus = 2;
                        weakSelf.overallSetting.printerSetting.printerBleName = printName;
                        [Manager stopScan];
                        self.signal = 1;
                    }else {
                        if (self.signal == 0) {
                            self.printerStatus = @"打印机未连接";
                            self.printerName = @"Printer";
                            self.overallSetting.printerSetting.printerStatus = 0;
                            [self.tableView reloadData];
                        }
                    }
                }];
            }
        }
        if (i == 60) {
            self.signal = 0;
            self.printerStatus = @"打印机未连接";
            [self.tableView reloadData];
            [Manager stopScan];
        }
    }];
}

//判断类型
-(void)ecsAndTsp {
    
    self.printerName = self.overallSetting.printerSetting.printerBleName;
    [SAValueManger shareInStance].printType = 2;
    self.printerStatus = @"打印机已连接";
    [self.tableView reloadData];
    
    NSString *printName = kPrint;
    NSString *printOpen = kPrintOpen;
    NSString *printType = kPrintType;
    // 二维码模块大小 1~16
    if ([printName isEqualToString:@"MHT-L58G"] || [printName isEqualToString:@"XP-T202UA"] || ([printOpen integerValue] == 1 && [printName isEqualToString:@"MHT-P18L"] && [printType integerValue] == 2)) {
        [self timerFired];
        self.signal = 0;
    }else if ([printName isEqualToString:@"MHT-P58D"] || [printName isEqualToString:@"YDT-XP"] || ([printOpen integerValue] == 1 && [printName isEqualToString:@"MHT-P18L"] && [printType integerValue] == 1)) {
        NSLog(@"esc");
        [SAValueManger shareInStance].printType = 1;
        [self connectionBluetooth];
    }else {
        unsigned char tscCommand[] = {0x1B, 0x21, 0x3F};
        NSData *tscData = [NSData dataWithBytes:tscCommand length:sizeof(tscCommand)];
        if ([printName isEqualToString:@"MHT-P18L"]) {
            unsigned char tscCommand2[] = {0x10, 0xF0, 0xC1};
            tscData = [NSData dataWithBytes:tscCommand2 length:sizeof(tscCommand2)];
        }
        __block NSString *isReceive = @"0";
        Manager.connecter.readData = ^(NSData * _Nullable data) {
            if ([printName isEqualToString:@"MHT-P18L"]) {
                NSMutableString *hexStr = [NSMutableString string];
                int8_t *bytes = (int8_t *)[data bytes];
                for (int i = 0; i < [data length]; i++) {
                    [hexStr appendFormat:@"%02X",bytes[i]];
                }
                if ([hexStr containsString:@"10F0C10101"]) {
                    isReceive = @"1";
                }
            } else {
                isReceive = @"1";
            }
        };
        [Manager write:tscData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (![isReceive isEqualToString:@"1"]) {
                //esc查询状态指令
                NSLog(@"esc");
                [SAValueManger shareInStance].printType = 1;
                [self connectionBluetooth];
            }else {
                NSLog(@"tsc");
                [self timerFired];
                self.signal = 0;
            }
        });
    }
}

-(void)connectionBluetooth {
    /* 连接外设（先停止扫描，然后断开之前连接，再连接当前外设）*/
    if (self.isConnection == NO) {
        return;
    }
    [Manager close];
    [[BluetoothManager sharedInstance] cancelConnect];//断开小票打印机
    
    __block int i = 0;
    __block int printNum = 0;
    __block CBPeripheral *newPeripheral = nil;
    [[BluetoothManager sharedInstance] scanWithSuccess:^(NSArray<CBPeripheral *> * _Nonnull peripheralArray) {
        NSLog(@"scanWithSuccess：%lu",(unsigned long)peripheralArray.count);
        i++;
        if (i == 100) {
            self.printerStatus = @"打印机未连接";
            self.overallSetting.printerSetting.printerStatus = 0;
            [self.tableView reloadData];
            [[BluetoothManager sharedInstance] stopScan];
            return;
        }
        
        for (CBPeripheral *peripheral2 in peripheralArray) {
            if ([peripheral2.name isEqualToString:self.overallSetting.printerSetting.printerBleName]) {
                newPeripheral = peripheral2;
            }
        }
        
        if (newPeripheral != nil && printNum == 0) {
            printNum++;
            [[BluetoothManager sharedInstance] stopScan];
            [[BluetoothManager sharedInstance] connect:newPeripheral didConnectPeripheral:^(CBPeripheral * _Nonnull peripheral) {
                // 打印机已连接
                self.overallSetting.printerSetting.printerStatus = 2;// 0-打印机未连接    1-打印机正在连接    2-打印机已连接
                self.overallSetting.printerSetting.printerBleName = peripheral.name;
                self.overallSetting.printerSetting.printType = 1;
                self.overallSetting.printerSetting.peripheral = peripheral;
                self.printerName = peripheral.name;
                self.printerStatus = @"打印机已连接";
                self.signal = 0;
                [self timerFired];
                [self.tableView reloadData];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"kOverallSettingDidChanged" object:nil];
                [SAValueManger shareInStance].oldPrint = NO;
                //根据目前适配的打印机，命名规则都不同，现在根据命名区分打印机型号，黑色打印机的在大家二维码的时候会有问题，如果后期有改动这里
                //要想办法处理二维码大小问题！
                NSArray<NSString *> *nameMarr = [peripheral.name componentsSeparatedByString:@"_"];
                if (nameMarr.count == 2) {
                    if ([@"Printer" isEqualToString:nameMarr[0]]) {
                        [SAValueManger shareInStance].oldPrint = YES;
                    }
                }
            } didFailToConnectPeripheral:^(CBPeripheral * _Nonnull peripheral, NSError * _Nonnull error) {
                // 打印机连接失败
                self.overallSetting.printerSetting.printerStatus = 0;// 0-打印机未连接    1-打印机正在连接    2-打印机已连接
                self.overallSetting.printerSetting.printerBleName = @"";
                [[NSNotificationCenter defaultCenter] postNotificationName:@"kOverallSettingDidChanged" object:nil];
                self.printerName = @"Printer";
                self.printerStatus = @"打印机未连接";
                self.signal = 0;
                [self.tableView reloadData];
            } didDisconnectPeripheral:^(CBPeripheral * _Nonnull peripheral, NSError * _Nonnull error) {
                // 打印机失去连接
                self.overallSetting.printerSetting.printerStatus = 0;// 0-打印机未连接    1-打印机正在连接    2-打印机已连接
                self.overallSetting.printerSetting.printerBleName = @"";
                [[NSNotificationCenter defaultCenter] postNotificationName:@"kOverallSettingDidChanged" object:nil];
                self.printerName = @"Printer";
                self.printerStatus = @"打印机未连接";
                self.signal = 0;
                [self.tableView reloadData];
            }];
        }
    } failure:^(CBCentralManagerState state, NSString * _Nonnull stateMessage) {
        NSLog(@"scanWithFailure：%ld，%@",(long)state, stateMessage);
        [Prompt popPromptViewWithMsg:stateMessage duration:2];
    }];
}

-(void)timerFired {
    if ([SAOverallSetting shareInstance].printerSetting.printerStatus == 2) {
        if (kIsTestServer == 1) {
            self.cloudPrintHeartbeatAPI.deviceToken = kDeviceToken;
            self.cloudPrintHeartbeatAPI.deviceType = @"2";
            self.cloudPrintHeartbeatAPI.merchantId = [SAValueManger shareInStance].userInfo.merchantId;
            self.cloudPrintHeartbeatAPI.os = @"2";
            self.cloudPrintHeartbeatAPI.printerType = 1;
            if ([SAValueManger shareInStance].printType == 2) {
                self.cloudPrintHeartbeatAPI.printerType = 2;
            }
            [self.cloudPrintHeartbeatAPI submitForm:POST];
        }
    }
}

-(void)startTime {
    self.count = 3;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired2) userInfo:nil repeats:YES];
}

- (void)timerFired2 {
    if (self.count != 1) {
        self.count -= 1;
    } else {
        self.isTip = YES;
        // 停掉定时器
        [self.timer invalidate];
        self.timer = nil;
    }
}


@end
